package com.lsh.util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;

/**
 * @author Administrator
 * @date 2019/11/02 17:03
 */

@Component
public class RedisUtil {

    @Autowired
    RedisTemplate redisTemplate;

    private int pageNum; //当前页码
    private int pageSize; //每页数据量
    private Long total; //总数据量
    private int firstIndex; //当前页的首索引
    private int lastIndex; //当前页的末索引
    private int pages; //总页数

    /**
     * list集合分页
     * @param listName
     * @param pageNum
     * @param pageSize
     * @return
     */
    public HashMap<String, Object> startPage(String listName, int pageNum, int pageSize){
        total = redisTemplate.opsForList().size(listName);
        pages = (int) (total / pageSize);
        if(total % pageSize != 0) ++pages;
        HashMap map = new HashMap();
        List list = null;
        if(pageNum > pages){
            return map;
        } else{
            firstIndex = pageSize * (pageNum - 1);
            lastIndex = pageSize * pageNum - 1;
            if(lastIndex > (total - 1)) lastIndex = (int) (total - 1);
            list = redisTemplate.opsForList().range(listName, firstIndex, lastIndex);
        }
        map.put("firstIndex", firstIndex);
        map.put("lastIndex", lastIndex);
        map.put("total", total);
        map.put("current", pageNum);
        map.put("pageSize", pageSize);
        map.put("pages", pages);
        map.put("list", list);
        return map;
    }


}
